package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long id : dictIds) {
            // 根据id查询bpmn对象
            BpmnInfo bpmnInfo = this.get(id);
            // 删除bpmnInfo对象
            bpmnInfoMapper.deleteByPrimaryKey(id);
            // TODO
            // 查询目前这个流程定义正在运行的流程实例
            // 把流程实例关联的BusinessKey找到业务对象
            // 获取流程定义对象
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .deploymentId(bpmnInfo.getDeploymentId())
                    .singleResult();
            // 删除Activiti中的流程定义对象
            repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
            // 把服务器上的文件删除
            String resourceName = processDefinition.getResourceName();
            File file = new File(SystemConfig.getProfile(), resourceName);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    @Transactional
    public void deploy(String bpmnInfoPath, String bpmnType, String info) throws FileNotFoundException {
        Deployment deploy = null;
        deploy = repositoryService.createDeployment()
                .addInputStream(bpmnInfoPath, new FileInputStream(new File(SystemConfig.getProfile(), bpmnInfoPath)))
                .deploy();
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeployTime(new Date());
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setInfo(info);
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId()).singleResult();
        bpmnInfo.setBpmnName(definition.getName());
        bpmnInfo.setActProcessId(definition.getId());
        bpmnInfo.setActProcessKey(definition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public InputStream getResourceByType(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        if ("xml".equalsIgnoreCase(type)) {
            return repositoryService.getResourceAsStream(deploymentId,definition.getResourceName());
        } else if("png".equalsIgnoreCase(type)){
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            // generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面是哪个参数都表示字体)
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST,Collections.EMPTY_LIST,"楷体","楷体","楷体");
            return inputStream;
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String bpmnType) {
        return bpmnInfoMapper.selectByType(bpmnType);
    }
}
